package com.study.samsung.Control;

import com.alibaba.fastjson.JSONObject;
import com.study.samsung.Entity.*;
import com.study.samsung.Service.*;
import com.study.samsung.Utils.BaseServlet;
import com.sun.org.apache.bcel.internal.generic.IINC;
import com.sun.org.apache.xpath.internal.operations.Or;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@WebServlet("/orderXq")
public class OrderXqServlet extends BaseServlet {
    AddressService as = new AddressService();
    DetailService ds = new DetailService();
    OrderXqService os = new OrderXqService();
    MyOrdersService ms = new MyOrdersService();
    IndexSearchService iss = new IndexSearchService();

    GoodsService gds = new GoodsService();


    @Override
    public String excute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Commodity> newgoods = iss.selectnew();
        List<Succession> selectxl = iss.selectxl();

        request.setAttribute("newgoods",newgoods);
        request.setAttribute("selectxl",selectxl);


        System.out.println("到达orderxqselect");
        Integer integer = (Integer) session.getAttribute("sxid");
        List<Detail> list = ds.selectGoodsxq(integer);
        System.out.println("商品详情进："+list);

//        List<Integer> integers = new ArrayList<>();

////        List<OrderDetails> orderDetails = os.selectAll();
////
////        Integer gnumber =  (orderDetails.size()*5)+orderDetails.stream().collect(Collectors.summingInt(OrderDetails::getGnumber));
            Double dxprice=0.0;
            for (int i = 0; i < list.size(); i++) {
                dxprice += list.get(i).getXprice().doubleValue();
            }
////        List<Integer> integers = new ArrayList<>();
////        orderDetails.forEach(b->{
////            integers.add(b.getSxid());
////        });
////        System.out.println(orderDetails);
        User users = (User) session.getAttribute("user");
        Integer uid = users.getUid();
        List<Address> addresses = as.servletAll(uid);
//        List<Detail> list = ds.selectGoodsxq(integers);
////        session.setAttribute("gnumber",gnumber);
         double dtotal = dxprice*(Integer)session.getAttribute("nums");
        System.out.println(dtotal);
            session.setAttribute("dxprice",dxprice);
////        session.setAttribute("orderxq",orderDetails);
        session.setAttribute("gnumber",session.getAttribute("nums"));
        session.setAttribute("dtotal",dtotal);
        session.setAttribute("goodsdetail",list);
        request.setAttribute("address",addresses);
//        System.out.println("list商品详情:"+list);

        return "f:orderXq";
    }



    public String addressStyle(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("utf-8");
        //设置响应内容的主体格式，是json格式的
        response.setContentType("application/json'charset=utf-8");
        User users = (User) session.getAttribute("user");
        Integer uid = users.getUid();
        List<Address> list =  as.servletAll(uid);
        String json = JSONObject.toJSONString(list);
        return json;
    }

    public String addnewAddress(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("utf-8");
        String addressname = request.getParameter("addressname");
        String sheng = request.getParameter("sheng");
        String shi = request.getParameter("shi");
        String qu = request.getParameter("qu");
        String aname = request.getParameter("aname");
        String aphone = request.getParameter("aphone");
        User users = (User) session.getAttribute("user");
        Integer uid = users.getUid();
        String s;
        Address address = new Address(null,addressname,sheng,shi,qu,aname,aphone,1,uid);
        Integer r = as.addAddress(address);
        if (r>0){
            s = "成功添加地址！";
        }else{
           s="地址添加失败，请重新添加";
        }
        return s;
    }

    public Integer Upisdefault(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("utf-8");

        String a = request.getParameter("a");
        int i = Integer.parseInt(a);
        Integer b = as.changeIsdefault(i);
        if (b>0){
            return 1;
        }else{
            return 0;
        }
    }
    public Integer delAddress(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("utf-8");
        String val = request.getParameter("val");
        System.out.println(val);
        Integer a = Integer.parseInt(val);
        Integer b = as.delAddress(a);
        return b;
    }

    public String selectOne(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("utf-8");

        String val = request.getParameter("val");
        System.out.println(val);
        Integer a = Integer.parseInt(val);
        Address address = as.selectOne(a);
        String json = JSONObject.toJSONString(address);
        System.out.println(json);
        return json;
    }

    public String bianjiAddress(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("utf-8");
        String jaid = request.getParameter("jaid");
        String addressname = request.getParameter("addressname");
        String sheng = request.getParameter("sheng");
        String shi = request.getParameter("shi");
        String qu = request.getParameter("qu");
        String aname = request.getParameter("aname");
        String aphone = request.getParameter("aphone");
        Integer aid = Integer.parseInt(jaid);
        User users = (User) session.getAttribute("user");
        Integer uid = users.getUid();
        String s;
        Address address = new Address(aid,addressname,sheng,shi,qu,aname,aphone,0,uid);
        Integer r = as.bianjiAddress(address);
        if (r>0){
            s = "地址编辑成功！";
        }else{
            s="地址编辑失败，请重新编辑";
        }
        return s;
    }

    public String ordersinsert(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("utf-8");
        Date date = new Date();
        SimpleDateFormat dateFormat_min=new SimpleDateFormat("YY-MM-dd HH:mm:ss");
        String format = dateFormat_min.format(date);
        String year = format.substring(0,2);
        String month = format.substring(3,5);
        String day = format.substring(6,8);
        String hour = format.substring(9,11);
        String minute = format.substring(12,14);
        String second = format.substring(15,17);
        String dxnumber = "SAM"+year+month+day+hour+minute+second;
        String dtime = format;
        String dstatus = request.getParameter("dstatus");
        String pay = request.getParameter("pay");
        Double dtotal = Double.parseDouble(request.getParameter("dtotal"));
        String Aid = request.getParameter("aid");
        int aid = Integer.parseInt(Aid);
        User users = (User) session.getAttribute("user");
        Integer uid = users.getUid();
        Integer r = os.ordersinsert(dxnumber,dtime,dstatus,pay,dtotal,uid,aid);
        Integer did = ms.selectId();
        System.out.println("插入订单表的订单id:"+did);
        session.setAttribute("did",did);
        if (session.getAttribute("goodsdetail")!=null){
            List<Detail> goodsdetail =  (List<Detail>) session.getAttribute("goodsdetail");
            System.out.println("商品详情进后查看插入数据："+goodsdetail);
            BigDecimal xprice = goodsdetail.get(0).getXprice();
            Integer gnumber =   (Integer) session.getAttribute("nums");
            int sxid = goodsdetail.get(0).getSxid();
            Integer osinsert = os.ordersxqinsert(xprice, gnumber, sxid, did);
            if (osinsert>0){
                return "创建订单成功！";
            }else{
                return "创建订单失败！";
            }

        }else {
            List<ShoppingCart> goodsdetail1 =  (List<ShoppingCart>) session.getAttribute("goodsdetail1");
            System.out.println("购物车进后查看插入数据："+goodsdetail1);
            Integer ordersxqinserts = os.ordersxqinserts(goodsdetail1, did);
            if (ordersxqinserts>0){
                return "创建订单成功！";
            }else {
                return "创建订单失败！";
            }
        }

    }

    public String shoppingin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("utf-8");
        List<Integer> nums = new ArrayList<>();
        List<Integer> price = new ArrayList<>();
        System.out.println("购物车进入：");

        User users = (User) session.getAttribute("user");
        Integer uid = users.getUid();
        List<Address> addresses = as.servletAll(uid);
        request.setAttribute("address",addresses);


        List<ShoppingCart> cartsdata = (List<ShoppingCart>)session.getAttribute("cartsdata");
        System.out.println(cartsdata);
        cartsdata.forEach(x->{
            nums.add(x.getGnum());
            price.add(x.getDetail().getXprice().intValue()*x.getGnum());
        });
        int sum = nums.stream().reduce(Integer::sum).orElse(0);
        int dtotal = price.stream().reduce(Integer::sum).orElse(0);
        System.out.println(sum);
        System.out.println(dtotal);
        session.setAttribute("goodsdetail1",cartsdata);
        session.setAttribute("gnumber",sum);
        session.setAttribute("dtotal",dtotal);
        List<Integer> integers = new ArrayList<>();
        session.getAttribute("cartsdata");

        List<Commodity> newgoods = iss.selectnew();
        List<Succession> selectxl = iss.selectxl();

        request.setAttribute("newgoods",newgoods);
        request.setAttribute("selectxl",selectxl);

        Object user = session.getAttribute("user");
        if (user!=null){
            User nowuser = (User) user;
            Integer uids = nowuser.getUid();

            session.setAttribute("cartcount",gds.cartcount(uids));
        }
        return ("f:orderXq");
    }

}
